package pl.darbat.incomecalc;

import pl.darbat.incomecalc.view.SeekBarPreference;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.util.Log;

public class TaxPreferenceActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener, OnPreferenceChangeListener {

	private static final String TAG = "TaxPreferenceActivity";
	private ListPreference mYear;
	private ListPreference mObtainCostPerMonth;
	private SeekBarPreference mRoyalityPercent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Load the preferences from an XML resource
		addPreferencesFromResource(R.xml.preferences);
		
	    mYear = (ListPreference) getPreferenceScreen().findPreference("year");
	    //mYear.setOnPreferenceChangeListener(this);
	    mObtainCostPerMonth = (ListPreference) getPreferenceScreen().findPreference("obtain_cost_per_month");
	    //mObtainCostPerMonth.setOnPreferenceChangeListener(this);
	    mRoyalityPercent = (SeekBarPreference) getPreferenceScreen().findPreference("royalty_percent2");
	    mRoyalityPercent.setOnPreferenceChangeListener(this);
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		Preference pref = findPreference(key);
		if (pref instanceof ListPreference) {
			ListPreference listPref = (ListPreference) pref;
			pref.setSummary(listPref.getEntry());
		}
		
	}


	@Override
	protected void onResume() {
		super.onResume();
		mYear.setSummary(mYear.getEntry());
		mObtainCostPerMonth.setSummary(mObtainCostPerMonth.getEntry());
		mRoyalityPercent.setSummary(Integer.toString(mRoyalityPercent.getProgress()) + " %");
		
	    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

	}
	
	@Override
	protected void onPause() {
		super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); 
	}

	public boolean onPreferenceChange(Preference pref, Object newValue) {
		if (pref instanceof ListPreference) {
			ListPreference listPref = (ListPreference) pref;
			pref.setSummary(listPref.getEntry());
		} else if(pref instanceof SeekBarPreference) {
			pref.setSummary(Integer.toString((Integer)newValue) + " %");
		}
		return true;
	}

}
